# -*- coding: utf-8 -*-
from odoo import models, api, fields, tools
from odoo.exceptions import UserError
import re


class pro_plan(models.Model):

    _name = "proman.pro_plan"
    _description = "项目计划"
    _table = "proman_pro_plan"
    _order = "sequence"
    _inherit =  ['mail.thread', 'mail.activity.mixin', 'image.mixin']

    sequence = fields.Integer(string="排序",translate = 0)
    name = fields.Char(string="计划名称",help = '请输入计划名称',readonly = 1,store = 1,translate = 0)
    project_temp_id = fields.Many2one(string="项目模板",help = '请选择项目模板',comodel_name = 'proman.project_temp',translate = 0)
    year = fields.Date(string="年度",translate = 0)
    manage_department_id = fields.Many2one(string="管理机构",comodel_name = 'hr.department',default = lambda self: self.env.user.default_department,translate = 0)
    project_category_id = fields.Many2one(string="项目类型",help = '请输入项目类型',comodel_name = 'proman.project_category',translate = 0)
    project_id = fields.Many2one(string="项目名称",comodel_name = 'proman.project_base',related = 'project_temp_id.project_id',readonly = 1,store = 1,translate = 0)
    project_stage_id = fields.Many2one(string="项目阶段",comodel_name = 'proman.stage_category',default = lambda self:self.env['proman.stage_category'].search([('name','=','可行性研究')]),translate = 0)
    company_id = fields.Many2one(string="所属公司",comodel_name = 'res.company',default = lambda self:self.env.company,required = 1,translate = 0)
    file_no = fields.Char(string="文件号",translate = 0)
    partner_id = fields.Many2one(string="相关单位",comodel_name = 'res.partner',domain = [('is_company','=',True)],translate = 0)
    gogal = fields.Text(string="年度目标",translate = 0)
    currency_id = fields.Many2one(string="货币",comodel_name = 'res.currency',default = lambda self:self.env['res.currency'].search([('name','=','CNY')]),translate = 0)
    amount = fields.Monetary(string="总金额",help = '请输入总金额',translate = 0)
    user_id = fields.Many2one(string="部门负责人",comodel_name = 'res.users',translate = 0)
    create_department_id = fields.Many2one(string="录入单位",comodel_name = 'hr.department',translate = 0)
    url = fields.Char(string="相关链接",translate = 0)
    image = fields.Binary(string="相关照片1",translate = 0)
    image1 = fields.Binary(string="相关照片2",translate = 0)
    pro_plan_funds = fields.One2many(string="资金计划",comodel_name = 'proman.pro_plan_fund',inverse_name = 'main_id',copy = 1,translate = 0)
    pro_plan_tasks = fields.One2many(string="任务内容",comodel_name = 'proman.pro_plan_task',inverse_name = 'main_id',copy = 1,translate = 0)
    pro_plan_indicators = fields.One2many(string="绩效目标",comodel_name = 'proman.pro_plan_indicator',inverse_name = 'main_id',copy = 1,translate = 0)
    memo = fields.Html(string="备注说明",translate = 0)
    attachment = fields.Many2many(string="相关附件",comodel_name = 'ir.attachment',translate = 0)
    state = fields.Selection(string="状态",selection = [('1', '草稿'), ('2', '提交'), ('3', '审核')],default='1',translate = 0)
    is_copy = fields.Boolean(string="是否为复制记录",default = 0,translate = 0)

    @api.onchange("year","manage_department_id","project_stage_id")
    def get_current_name(self):
        for plan in self:
            year = str(plan.year.year)+'年度-' if plan.year else ''
            department_name = plan.manage_department_id.name +"-" if plan.manage_department_id else ''
            p_state = plan.project_stage_id.name if plan.project_stage_id else ''
            plan.name = year +department_name  + p_state
    @api.onchange('project_temp_id')
    def compute_items_fields(self):
        for record in self:
            record.pro_plan_funds = False
            record.pro_plan_indicators = False
            record.pro_plan_tasks = False
            pro_plan_funds = []
            pro_plan_indicators = []
            pro_plan_tasks = []

            if record.project_temp_id:
                # 主表
                record.project_id = record.project_temp_id.project_id
                # 明细
                temp_pro_plan_funds = self.env['proman.project_temp_fund'].sudo().search([('main_id', '=', record.project_temp_id.id)], order='sequence')
                for temp_pro_plan_fund in temp_pro_plan_funds:
                    pro_plan_fund = {
                        "fund_id": temp_pro_plan_fund.fund_id.id,
                        'uom_id': temp_pro_plan_fund.uom_id.id,
                        "currency_id" : temp_pro_plan_fund.currency_id.id
                    }
                    pro_plan_funds.append((0, 0, pro_plan_fund))

                temp_pro_plan_indicators = self.env['proman.project_temp_indicator'].sudo().search([('main_id', '=', record.project_temp_id.id)], order='sequence')
                for temp_pro_plan_indicator in temp_pro_plan_indicators:
                    pro_plan_indicator = {
                        "indicator_category_id": temp_pro_plan_indicator.indicator_category_id.id,
                        'indicator_id': temp_pro_plan_indicator.indicator_id.id,
                        'uom_id': temp_pro_plan_indicator.uom_id.id,
                    }
                    pro_plan_indicators.append((0, 0, pro_plan_indicator))

                temp_pro_plan_tasks = self.env['proman.project_temp_task'].sudo().search([('main_id', '=', record.project_temp_id.id)], order='sequence')
                for temp_pro_plan_task in temp_pro_plan_tasks:
                    pro_plan_task = {
                        "indicator_category_id": temp_pro_plan_task.indicator_category_id.id,
                        "indicator_id": temp_pro_plan_task.indicator_id.id,
                        "uom_id": temp_pro_plan_task.uom_id.id,
                    }
                    pro_plan_tasks.append((0, 0, pro_plan_task))

                record.update({
                    "pro_plan_funds": pro_plan_funds,
                    "pro_plan_indicators": pro_plan_indicators,
                    "pro_plan_tasks": pro_plan_tasks,
                })

    def button1(self):
        if self.state == '1':
            self.write({'state': '2'})
        # 审核
    def button2(self):
        if self.state == '2':
            self.write({'state': '3'})
        # 退回
    def button3(self):
        if self.state == '2':
            self.write({'state': '1'})

        # 反审核
    def button4(self):
        if self.state == '3':
            self.write({'state': '2'})


    @api.returns('self', lambda value: value.id)
    def copy(self, default=None):
        self.ensure_one()
        default = dict(default or {})
        if 'is_copy' not in default:
            default['is_copy'] = True
        return super(pro_plan, self).copy(default=default)
    def unlink(self):
        for record in self:
            if record.state != '1':
                raise UserError("非草稿数据，不可删除，请取消并检查！")
        res = super(pro_plan, self).unlink()
        return res

    @api.model
    def create(self, vals):
        old_name = vals.get("name", "")
        if vals.get("is_copy",False) and old_name:
            vals.update({"name":old_name+"_复制"})
        check_datas = [
            {'fieldname': 'pro_plan_funds', 'checkfields': [['amount']]},
            {'fieldname': 'pro_plan_tasks', 'checkfields': [['quantity'], ['price']]},
            {'fieldname': 'pro_plan_indicators', 'checkfields': [['value']]},
        ]
        # [[，或的关系], 且的关系]
        # 支持 'integer', 'float','char', 'monetary' 四种类型
        vals = self.compute_creat_value(vals, check_datas)
        return super(pro_plan, self).create(vals)


    def write(self, vals):
        vals['is_copy'] = False
        check_datas = [
            {'fieldname': 'pro_plan_funds', 'checkfields': [['amount']]},
            {'fieldname': 'pro_plan_tasks', 'checkfields': [['quantity'], ['price']]},
            {'fieldname': 'pro_plan_indicators', 'checkfields': [['value']]},
        ]
        vals = self.compute_write_value(vals, check_datas)
        return super(pro_plan,self).write(vals)